<template>
  <view>
    <button open-type="getUserInfo" @getuserinfo="getMyInfo">点我登录</button>
  </view>
</template>

<script>
export default {
  methods: {
    // 获取用户信息
    getMyInfo (userInfoRes) {
      let { encryptedData, rawData, iv, signature } = userInfoRes.mp.detail
      // 获取code
      wx.login({
        success: async ({ code }) => {
          // 发请求
          let data = await this.$request({
            url: '/api/public/v1/users/wxlogin',
            method: 'POST',
            data: {
              code,
              encryptedData,
              rawData,
              iv,
              signature
            }
          })
          // 存储token并提示
          wx.setStorageSync('token', data.token)
          // 存用户信息
          wx.setStorageSync('userInfo', userInfoRes.mp.detail.userInfo)
          wx.showToast({
            title: '登录成功',
            success: () => {
              // 等toast消失跳转
              setTimeout(() => {
                // 返回上一个页面
                wx.navigateBack()
              }, 1500)
            }
          })
        }
      })
    }
  }
}
</script>

<style></style>
